<?php

namespace App\Console\Commands\SiteLocation;

use App\Models\OpenShop\Common\SiteLocationMallModel;
use App\Models\Wanggui\CustomerDepartmentTaskModel;
use App\Service\Common\AreaService;
use Illuminate\Console\Command;

class AddSiteTask extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'siteLocation:add-site-task';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '添加堪址任务';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     */
    public function handle()
    {
        $userMapping = [
            '远山和叶' => 4460,
            '花蝴蝶'   => 7416,
            '唐昊'     => 7099,
            '梅维斯'   => 7141,
            '龙亚'     => 7095,
            '景元'     => 6690,
            '功仔'     => 7094,
        ];


        CustomerDepartmentTaskModel::query()->truncate();
        ini_set('memory_limit', '1024M');


        $fileContent = file_get_contents('https://file.51kuafu.com/e4/b4/1c5c6784df97ad4c81c367d990d041a0c01347aa7276d0bd86341ea8a200.csv');
        $listTemp    = explode("\r\n", $fileContent);
        $assignList  = [];
        foreach ($listTemp as $value) {
            $arr          = explode(',', $value);
            $assignList[] = [
                'mallId'  => $arr[0] ?? '',
                'ranking' => $arr[1] ?? '',
                'userId'  => $userMapping[$arr[2] ?? ''] ?? 0,
            ];
        }

        $insertTaskData = [];
        SiteLocationMallModel::query()
            ->where('grade', '>', 0)
            ->chunkById(20, function ($siteLocations) use (&$insertTaskData, $assignList) {
                foreach ($siteLocations as $location) {

                    if (in_array($location->province, ['台湾', '香港', '澳门'])) {
                        continue;
                    }

                    $regionInfo = AreaService::getAdcodeByProvinceCityDistrict($location->province, $location->city, $location->district);

                    // 获得地址
                    if (!$location->lat || !$location->lng) {
                        continue;
                    }

                    $this->info($location->mallName);

                    // 通过商场ID获得绑定关系
                    $assignInfo   = collect($assignList)->where('mallId', $location->mallId)->first();
                    $projectPhase = 0;
                    if ($location->settle) {
                        $manageStatus = CustomerDepartmentTaskModel::MANAGE_STATUS_COMPLETE;
                        $projectPhase = CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM;
                    } else {
                        if (($assignInfo['userId'] ?? 0) > 0) {
                            $manageStatus = CustomerDepartmentTaskModel::MANAGE_STATUS_ASSIGN;
                            $projectPhase = CustomerDepartmentTaskModel::PROJECT_PHASE_WAIT_FOLLOW_UP;
                        } else {
                            $manageStatus = CustomerDepartmentTaskModel::MANAGE_STATUS_WAIT_ASSIGN;
                        }
                    }

                    $insertTaskData[] = [
                        'wgNumber'      => $location->wgNumber,
                        'wgName'        => $location->mallName,
                        'wgType'        => CustomerDepartmentTaskModel::WG_TYPE_MALL,
                        'manageStatus'  => $manageStatus,
                        'projectPhase'  => $projectPhase,
                        'grade'         => $location->grade,
                        'address'       => $location->address,
                        'ranking'       => $assignInfo['ranking'] ?? 0,
                        'assignId'      => $assignInfo['userId'] ?? 0,
                        'assignTime'    => ($assignInfo['userId'] ?? 0) ? time() : 0,
                        'settle'        => $location->settle,
                        'prefixAddress' => $regionInfo['province']['name'] . '-' . $regionInfo['city']['name'] . '-' . $regionInfo['district']['name'],
                        'provinceCode'  => $regionInfo['province']['code'],
                        'cityCode'      => $regionInfo['city']['code'],
                        'districtCode'  => $regionInfo['district']['code'],
                        'createdAt'     => time(),
                        'updatedAt'     => time(),
                    ];
                }
            });

        $insertData = array_chunk($insertTaskData, 50);

        foreach ($insertData as $datum) {
            CustomerDepartmentTaskModel::query()->insert($datum);
        }
    }
}
